<template>
  <div class="register">
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      class="register-box"
    >
      <p>用户登录</p>
      <el-form-item prop="phone">
        <el-input
          type="text"
          placeholder="输入账号"
          v-model="ruleForm.phone"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item prop="pass">
        <el-input
          type="password"
          placeholder="输入密码"
          v-model="ruleForm.pass"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="buttton" type="primary" @click="submitForm"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { user_login } from "../utils/api";
export default {
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (!/^\d{6}$/.test(value)) {
        callback(new Error("密码格式不正确"));
      } else {
        callback();
      }
    };
    
    return {
      ruleForm: {
        phone: "",
        pass: ""
      },
      rules: {
        phone: [{ validator: validatePhone, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }],
      },
    };
  },
  computed:{

  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //发起登录请求.
          user_login(this.ruleForm).then((res) => {
            if (res.data.code == 200) {
              this.$message({ message: res.data.msg, type: "success" });
              // 储存token
              localStorage.setItem('token',res.data.token)
              // 储存用户信息
              this.$store.commit('setUser',res.data.userinfo);
              // 过滤路由
              this.$router.addRoutes( this.$store.getters.getRoute );
              // 跳转主界面
              this.$router.push('/index')
              location.reload()
            } else {
              this.$message({ message: res.data.msg, type: "error" });
            }
          });
        } else {
          this.$message({ message: "请按要求填写信息", type: "error" });
        }
      });
    },
  },
};
</script>

<style lang='scss'>
.register {
  height: 100%;
  background: url(../assets/bg.png) no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  .register-box {
    background-color: #fff;
    width: 500px;
    padding: 40px;
    border-radius: 10px;
    p {
      font-size: 26px;
      color: #444444;
      margin-bottom: 20px;
    }
    .el-form-item__content {
      text-align: center;
    }
    .el-select {
      width: 100%;
    }
  }
}
</style>